package server

import (
	"context"
	"errors"
	"house-src/basic/config"
	__ "house-src/basic/proto"
	"house-src/untils"
	"math/rand"
	"strconv"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedHouseServer
}

// 短信
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {

	sms := untils.ALiYun{}

	//定义发送短信次数
	count := config.Rdb.Get(config.Ctx, "sendSmsErr"+in.Mobile).Val()
	if count >= "5" {
		return nil, errors.New("1分钟内最多发送5条短信")
	}

	code := rand.Intn(9000) + 1000

	err := sms.AliSendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, errors.New("短信发送失败")
	}

	//缓存
	config.Rdb.Set(config.Ctx, "sendSms"+in.Mobile, code, time.Hour)
	//发送次数自增
	config.Rdb.Incr(config.Ctx, "sendSmsErr"+in.Mobile)
	//限制时间
	config.Rdb.Expire(config.Ctx, "sendSmsErr"+in.Mobile, time.Minute*1)

	return &__.SendSmsResp{}, nil
}
